package zdh.avatar.gui;

import java.awt.event.*;
import zdh.avatar.base.*;

/**
 *
 * @author Gem Seeker
 */
public class ButtonHandler implements ActionListener {

    private int toggle;
    
    private ButtonGroups buttonGroups;
    private ChildGroup childGroup;
    private ElementButton button;
    private SoundClip[] clips;
    private int curClip;

    public ButtonHandler(ElementButton button, ButtonGroups buttonGroups) {
        toggle = 0;
        this.buttonGroups = buttonGroups;
        this.button = button;
        String[] paths = button.getAudioPaths();
        clips = new SoundClip[paths.length];

        for (int i = 0; i < paths.length; i++) {
            clips[i] = new SoundClip(paths[i]);
        }

        curClip = 0;
    }
    
    public ButtonHandler(ElementButton button, ChildGroup childGroup) {
        toggle = 1;
        this.childGroup = childGroup;
        this.button = button;
        String[] paths = button.getAudioPaths();
        clips = new SoundClip[paths.length];

        for (int i = 0; i < paths.length; i++) {
            clips[i] = new SoundClip(paths[i]);
        }

        curClip = 0;
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        /*
         * stop the current playing clip
         */
        if(toggle == 0){
            if (buttonGroups.getCurrentClip() != null) {
                buttonGroups.getCurrentClip().stop();
            }
        }else{
            if(childGroup.getCurrentClip() != null){
                childGroup.getCurrentClip().stop();
            }
        }

        clips[curClip].play();
        /*
         * load the next preferred buttons when clicked
         */
        if(toggle == 0){
            buttonGroups.loadChildButtons(button);
            buttonGroups.setCurrentClip(clips[curClip++].getClip());
        }else{
            childGroup.loadButtons(button);
            childGroup.setCurrentClip(clips[curClip++].getClip());
        }
        curClip %= clips.length;

        
    }
}
